package me.itsoo.artemis.framework.core.util;

import lombok.NoArgsConstructor;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * FrequencyHelper
 *
 * @author zxy
 * @version 0.0.1
 * @since 2023/6/4
 */
@NoArgsConstructor
public class FrequencyHelper {

    private static final int MAX_AGE = 15;

    private static final int MIN_FREQUENCY = (int) TimeUnit.SECONDS.toMillis(10L);

    private static final int MAX_FREQUENCY = (int) TimeUnit.MINUTES.toMillis(2L);

    ////////////////////////////////////
    //  Control frequency and period  //
    ////////////////////////////////////

    private final AtomicInteger age = new AtomicInteger(MAX_AGE);

    private final AtomicInteger frequency = new AtomicInteger(MIN_FREQUENCY);

    /**
     * 获取实例
     *
     * @return FrequencyHelper
     */
    public static FrequencyHelper create() {
        return new FrequencyHelper();
    }

    /**
     * 重置频率控制
     */
    public final void reset() {
        this.age.set(MAX_AGE);
        this.frequency.set(MIN_FREQUENCY);
    }

    /**
     * 获取频率控制
     *
     * @return int
     */
    public final int get() {
        return frequency.get();
    }

    /**
     * 自增并获取频率控制
     *
     * @return int
     */
    public final int incrementAndGet() {
        int f = frequency.get();
        if (f >= MAX_FREQUENCY) {
            f = MAX_FREQUENCY;
        } else if (age.decrementAndGet() < 0) {
            f = Math.min(MAX_FREQUENCY, f << 1);
        }

        for (; ; ) {
            if (frequency.compareAndSet(frequency.get(), f)) {
                return frequency.get();
            }
        }
    }
}
